<?php
/**
 *google code.com pass yU2bS4GA3YY2
 * Project: ShopWorx- making your life easier
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * @Author Chris
 * @File App.class.php
 * @Version 1.0.0
 * @Copyright 2008 Shopworx (c)
 * @Year 2008
 * @access Public
 */



/**
 * Application abstraction layer
 *
 *@package Application
 */

class Application
{

    function Application($param = null)
    {
        /**
         *  Initialize application
         */
        $this->app_name = $this->setDefault($param['app_name'], null);
        $this->app_version = $this->setDefault($param['app_version'], null);
        $this->app_type = $this->setDefault($param['app_type'], null);
        $this->app_db_url = $this->setDefault($param['app_db_url'], null);
        $this->debug_mode = $this->setDefault($param['app_debugger'], false);
        $this->auto_connect = $this->setDefault($param['app_auto_connect'], null);
        $this->auto_chk_session = $this->setDefault($param['app_auto_chk_session'], true);
        $this->auto_authorize = $this->setDefault($param['app_auto_authorize'], true);
        $this->session_ok = $this->setDefault($param['app_auto_authorize'], false);

        $this->error = array();
        $this->authorized = false;
        $this->base_url = sprintf("%s", $this->getServer());
        $this->app_path = APP_PATH;
        $this->template_dir = TEMPLATE_DIR;


        /**
         * If Debugger is on then create a debug object
         */
        if (defined("DEBUG_LOADED") && $this->debug_mode == true) {
            if (empty($param['debug_color'])) {
                $param['debug_color'] = 'red';
            }

            $this->debugger = new Debug(array('color' => $param['debug_color'], 'prefix' =>
                $this->app_name, 'buffer' => true));
			}
            /**
             * Load Error Handler
             */
            $this->has_error = null;

            $this->set_error_handler();

            /**
             * Start session
             */

            session_start();

            $this->user_id = (!empty($_SESSION['SESSION_USER_ID'])) ? $_SESSION['SESSION_USER_ID'] : null;
            $this->user_name = (!empty($_SESSION['SESSION_USERNAME'])) ? $_SESSION['SESSION_USERNAME'] : null;
            ;
            $this->user_email = (!empty($_SESSION['SESSION_USERNAME'])) ? $_SESSION['SESSION_USERNAME'] : null;
            ;
            $this->set_url();

            if ($this->auto_chk_session){
                $this->check_session();
                }
            if (!empty($this->app_db_url) && $this->auto_connect && !$this->connect()) {
                $this->alert('APP_FAILED');
            }

            if ($this->auto_authorize && !$this->authorize()) {
                $this->alert('UNAUTHORIZED_ACCESS');
            }
        
    }
    function getEmail()
    {
        return $this->user_email;
    }

    function getName()
    {
        list($name, $host) = explode('', $this->getEmail());
        return ucwords($name);
    }

    function check_session()
    {
        if ($this->session_ok == true) {
            return true;
        }

        if (!empty($this->user_name)) {
            $this->session_ok = true;
        } else {
            $this->session_ok = false;
            $this->reauthenticate();
        }

        return $this->session_ok;
    }

    function reauthenticate()
    {
        global $AUTHENTICATE_URL;
        header("location: $AUTHENTICATION_URL?url=$this->self_url");
    }

    function getBaseURL()
    {
        return $this->base_url;
    }

    function getServer()
    {
        $this->set_url();
        return $this->server;
    }

    function getAppPath()
    {
        return $this->app_path;
    }
    /**
     * Get a fully qualified app path
     */
    function getFQAN()
    {
        return sprintf("%s%s", $this->server, $this->app_path);
    }

    function getTemplateDir()
    {
        return $this->template_dir;
    }

    function set_url()
    {
        $row_protocol = $this->getEnvironment('SERVER_PROTOCOL');

        $port = $this->getEnvironment('SERVER_PORT');

        if ($port == 80) {
            $port = null;
        } else {
            $port = ':' . $port;
        }
        
        $protocol = strtolower(substr($row_protocol,0,strpos($row_protocol,'/')));
        $this->server = sprintf("%s://%s%s", $protocol, $this->getEnvironment('HTTP_HOST'),
            $port);

        $this->self_url .= sprintf("%s://%s%s%s", $protocol, $this->getEnvironment('HTTP_HOST'),
            $port, $this->getEnvironment('REQUEST_URI'));

    }

    function terminate()
    {
        if (isset($this->DBAL)) {
            if ($this->DBAL->connected) {
                $this->DBAL->disconnect();
            }
        }
        session_destroy();
        exit;
    }

    function authorize($username = null)
    {
        return false;
    }

    function set_error_handler()
    {
        if (defined("ERROR_HANDLER_LOADED")){
            $this->errHandler = new ErrorHandler(array('name' => $this->app_name));
            }
    }

    function getErrorMessage($code)
    {
        return $this->errHandler->error_message[$code];
    }

    function show_popup($code, $head, $flag = null)
    {
        return $this->errHandler->alert($code, $head, $flag);
    }

    function getMessage($code = null, $hash = null)
    {
        $msg = $this->messages[$this->language][$code];

        if (!empty($hash)) {
            foreach ($hash as $key => $value) {
                $key = '/{' . $key . '}/';
                $msg = preg_replace($key, $value, $msg);
            }
        }
        return $msg;
    }

    function alert($code = null, $flag = null)
    {
        return (defined("ERROR_HANDLER_LOADED")) ? $this->errHandler->alert($code, $flag) : false;
    }

    function buffer_debugging()
    {

        if (defined("DEBUG_LOADED") && $this->debug_mode == true) {
            $this->debugger->set_buffer();
        }
    }

    function dump_debuginfo()
    {

        if (defined("DEBUG_LOADED") && $this->debug_mode == true) {
            $this->debugger->flush_buffer();
        }
    }

    function debug($msg)
    {
        if ($this->debug_mode == true) {
            $this->debugger->write($msg);
        }
    }

    function run()
    {
        $this->writln("You need to override this method.");
    }

    function connect($db_url = null)
    {
        if (empty($db_url)) {
            $db_url = $this->app_db_url;
        }

        if (defined('DBAL_LOADED') && !empty($this->app_db_url)) {
            $this->db = new DBAL($db_url);
            return $this->db->connected;
        }

        return false;

    }

    function disconnect()
    {
        $this->dbal->disconnect();
        $this->dbal->connected = false;
        return $this->dbal->connected;
    }

    function get_error_message($code = null)
    {
        return $this->errHandler->get_error_message($code);
    }

    function show_debugger_banner()
    {
        global $ON;

        if ($this->debug_mode == $ON) {
            $this->debugger->print_banner();
        }
    }

    /**
     * Gets the Appliction version.
     */
    function get_version()
    {
        return $this->app_version;
    }

    /**
     * Gets the Application name.
     */
    function get_name()
    {
        return $this->app_name;
    }

    /**
     * Gets the Application type.
     */
    function get_type()
    {
        return $this->app_type;
    }

    function set_error($err = null)
    {
        if (isset($err)) {
            array_push($this->error, $err);
            $this->has_error = true;
            return 1;
        } else {
            return 0;
        }
    }

    function has_error()
    {
        return $this->has_error;
    }

    function reset_error()
    {
        $this->has_error = false;
    }

    function get_error()
    {
        return array_pop($this->error);
    }

    function get_error_array()
    {
        return $this->error;
    }

    function dump_array($a)
    {
        if (strstr($this->get_type(), 'WEB')) {
            echo '<pre>';
            print_r($a);
            echo '</pre>';
        } else {
            print_r($a);
        }
    }

    function dump()
    {
        if (strstr($this->get_type(), 'WEB')) {
            echo '<pre>';
            print_r($this);
            echo '</pre>';
        } else {
            print_r($this);
        }
    }

    function checkRequiredFields($fieldType = null, $fieldData = null, $errorCode = null)
    {
        $err = array();

        while (list($field, $func) = each($fieldType)) {
            $ok = $this->$func($fieldData[$field]);

            if (!$ok) {
                $this->alert($errorCode{$field});
            }
        }
        return $err;
    }

    function number($num = null)
    {
        if (is_array($num)) {
            foreach ($num as $i) {
                if (!is_numeric($i)) {
                    return 0;
                }
            }
            return 1;
        } else
            if (is_numeric($num)) {
                return 1;
            } else {
                return 0;
            }
    }

    function name($name = null)
    {
        if (strlen($email) < 5 || !strpos($email, '')) {
            return 0;
        } else {
            return 1;
        }

    }

    function currency($amount = null)
    {
        return 1;
    }

    function month($mm = null)
    {
        if ($mm >= 1 && $mm <= 12) {
            return 1;
        } else {
            return 0;
        }
    }

    function comboOption($optVal = null)
    {
        if ($optVal != 0) {
            return 1;
        } else {
            return 0;
        }
    }

    function day($day = null)
    {
        if ($day >= 1 && $day <= 31) {
            return 1;
        } else {
            return 0;
        }
    }

    function year($year = null)
    {
        return ($this->number($year));
    }

    function one_zero_flag($flag = null)
    {
        if ($flag == 1 || $flag == 0) {
            return 1;
        } else {
            return 1;
        }
    }

    function plain_text($text = null)
    {
        return 1;
    }

    function debug_array($hash = null)
    {
        $this->debugger->debug_array($hash);
    }

    function writeln($msg)
    {
        global $WWW_NEWLINE;
        global $NEWLINE;
        echo $msg, (strstr($this->app_type, 'WEB')) ? $WWW_NEWLINE : $NEWLINE;
    }

    function set_escapedVar($hash)
    {
        while (list($key, $value) = each($hash)) {
            $this->escapedVarHash {
                $key}
            = preg_replace("/\s/", "+", $value);
        }
    }

    function get_escapedVar($key)
    {
        return $this->escapedVarHash {
            $key}
        ;
    }

    function setUID($uid = null)
    {
        $this->user_id = $uid;
    }

    function getUID()
    {
        return $this->user_id;
    }

    function getUserName()
    {
        return $this->user_name;
    }

    function emptyError($field, $errCode)
    {
        if (empty($field)) {
            $this->alert($errCode);
        }
    }

    function getRequestField($field, $default = null)
    {
        return (!empty($_REQUEST[$field])) ? $_REQUEST[$field] : $default;
    }

    function getSessionField($field, $default = null)
    {
        return (!empty($_REQUEST[$field])) ? $_REQUEST[$field] : $default;
    }

    function setDefault($value, $default)
    {
        return (isset($value)) ? $value : $default;
    }

    function fileextension($filename)
    {
        return substr(basename($filename), strrpos(basename($filename), ".") + 1);
    }

    function getEnvironment($key)
    {
        return $_SERVER[$key];
    }
    
    function show_question($question = null)
    {
		  echo "<script src = \"Includes/libs/extjs/adapter/ext/ext-base.js\"></script>";
          echo "<script src = \"Includes/libs/extjs/ext-all.js\"></script>";
		  echo "<script>
				 Ext.MessageBox.show({
                     title: 'Question',
                     msg: '$question',
                     buttons: Ext.MessageBox.YESNOCANCEL,
                     icon: Ext.MessageBox.QUESTION
                 });
				 </script>";
		//TODO: create logic for button handling.
    }

}
